<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>小方块移动</title>
    <style>
        body {
            background-color: black;
        }

        #container {
            width: 600px;
            margin: 100px auto;
            display: flex;
            flex-wrap: wrap;
        }

        .square {
            width: 10px;
            height: 10px;
            margin-right: 2px;
            margin-bottom: 2px;
            background: rgba(38, 37, 37, 0.658);
        }
    </style>
</head>

<body>

    <div class="container" id="container"></div>

    <script>

        generateSquare()

        // 生成小方块
        function generateSquare() {
            const container = document.getElementById("container")
            for (let i = 0; i < 3000; i++) {
                const square = document.createElement("div");
                square.className = "square"
                // className 属性设置或返回元素的 class 属性。
                container.appendChild(square);
            }

            container.onmouseover = function (e) {
                let target = e.target
                if (target.className == "square") {
                    setColor(target)
                }
            }
            container.onmouseout = function (e) {
                let target = e.target
                if (target.className == "square") {
                    deleteColor(target)
                }
            }
        }



        function setColor(element) {
            // console.log(Math.floor(Math.random() * 256));
            function getNum() {
                return Math.floor(Math.random() * 256)
            }
            element.style.backgroundColor = `rgb(${getNum()},${getNum()},${getNum()})`
        }

        function deleteColor(element) {
            element.style.transition = '1.2s'
            element.style.backgroundColor = ''
        }

    </script>
</body>

</html>